package bdhub.littletail.lib.net.listener;

import android.widget.Toast;

import bdhub.littletail.app.LittleTailApplication;
import bdhub.littletail.lib.config.CConfig;
import bdhub.littletail.lib.net.volley.BusinessError;
import bdhub.littletail.lib.net.volley.VolleyError;
import bdhub.littletail.lib.utils.common.CThreadUtils;

/**
 * Created by Freddy on 2016/2/23.
 * chenshichao@outlook.com
 * 网络请求回调类
 */
public abstract class OnResponseListener<T> {

    /**
     * 上一次提示网络错误的时间（避免不断重复提示网络错误，根据时间间隔提示）
     */
    private static long lastTipsNetworkErrorTime = 0;

    /**
     * 缓存加载失败
     */
    public void onNoCache() {

    }

    /**
     * 缓存加载成功
     * @param response
     */
    public void onCacheLoaded(T response) {
        onBusinessSuccessed(response);
    }

    /**
     * 业务返回成功
     * @param response
     */
    public abstract void onBusinessSuccessed(T response);

    /**
     * 业务返回失败
     * 默认是弹出提示框提示错误信息<br />
     * 如需特别处理，请重载此方法
     * @param error
     */
    public void onBunsinessFailed(final BusinessError error) {
        if(CConfig.DEBUG) {
            CThreadUtils.runOnMainThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(LittleTailApplication.sharedInstance(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 网络请求任务结束（无论成功失败都会调用此方法）
     */
    public abstract void onFinished();

    /**
     * 与业务无关的失败处理
     * @param e
     */
    public void onNetworkError(VolleyError e) {
        if(System.currentTimeMillis() - lastTipsNetworkErrorTime > (6 * 1000)) {
            Toast.makeText(LittleTailApplication.sharedInstance(), "网络连接失败，请重试", Toast.LENGTH_SHORT).show();
            lastTipsNetworkErrorTime = System.currentTimeMillis();
        }
        e.getNetworkTimeMs();
    }
}
